<template>
  <div>
    <el-upload
      class="avatar-uploader"
      action=""
      :show-file-list="false"
      :on-success="handleAvatarSuccess"
      :before-upload="beforeAvatarUpload"
      :http-request="uploadImage"
    >
      <img
        v-if="value"
        :src="value"
        class="avatar"
        style="width: 100px; height: 60px"
      >
      <i v-else class="el-icon-plus avatar-uploader-icon" />
    </el-upload>
  </div>
</template>
<script>
// eslint-disable-next-line no-unused-vars
import COS from 'cos-js-sdk-v5'
export default {
  props: {
    value: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      imageUrl: ''
    }
  },
  methods: {
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
    },
    beforeAvatarUpload(file) {
      // 判断用户满足后面的四种格式

      const isJPG = [
        'image/jpeg',
        'image/png',
        'image/gif',
        'image/bmp'
      ].includes(file.type)
      //   const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 5

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG PNG GIF BMP 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 5MB!')
      }
      return isJPG && isLt2M
    },
    // 自定义上传图片
    uploadImage(files) {
      // files 拿到了上传的文件对象
      // 通过cos-sdk 上传到存储桶中
      console.log(files.file)
      // var COS = require('cos-js-sdk-v5')
      // 实例化
      // SECRETID 和 SECRETKEY 请登录 https://console.cloud.tencent.com/cam/capi 进行查看和管理
      var cos = new COS({
        SecretId: 'AKIDPyWSUUVQL5jkZJtzDIDzeHhU6RgozfFg',
        SecretKey: 'WBpT0LaedoDNhyM2b6hMvIUWQlwfJrKA'
      })
      cos.putObject(
        {
          /* 填入您自己的存储桶，必须字段 */
          Bucket: 'yzl815-1318717466',
          /* 存储桶所在地域，例如ap-beijing，必须字段 */
          Region: 'ap-beijing',
          /* 存储在桶里的对象键（例如1.jpg，a/b/test.txt），必须字段 */
          Body: files.file,
          Key: files.file.name,
          /* 必须，上传文件对象，可以是input[type="file"]标签选择本地文件后得到的file对象 */ // eslint-disable-next-line space-before-function-paren
          onProgress: function (progressData) {
            // 上传的进度
            console.log(JSON.stringify(progressData))
          }
        },
        (err, data) => {
          console.log(err || data)
          this.$emit('input', 'http://' + data.Location)
        }
      )
    }
  }
}
</script>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 60px;
  line-height: 60px;
  text-align: center;
}
.avatar {
  width: 100px;
  height: 60px;
}
</style>
